package com.ruoyi.ms.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Calendar;
import java.util.List;

import cn.hutool.core.collection.CollectionUtil;
import com.google.gson.Gson;
import com.ruoyi.common.constant.GlobalConstant;
import com.ruoyi.common.service.ICommonService;
import com.ruoyi.ms.constant.MsConstant;
import com.ruoyi.ms.domain.MsOrder;
import com.ruoyi.ms.domain.MsOrderIncome;
import com.ruoyi.ms.dto.MsPackageResDto;
import com.ruoyi.ms.dto.MsPackageResultResDto;
import com.ruoyi.ms.dto.MsOrderIncomeDetailResDto;
import com.ruoyi.ms.dto.MsOrderResDto;
import com.ruoyi.ms.mapstruct.MsPackageMap;
import com.ruoyi.ms.service.IMsOrderIncomeService;
import com.ruoyi.ms.service.IMsOrderService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.xp.order.dto.OrderDto;
import com.ruoyi.xp.order.dto.OrderIncomeDto;
import com.ruoyi.xp.order.dto.OrderInfoDto;
import com.ruoyi.xp.order.service.IOrderInfoService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.ms.mapper.MsPackageMapper;
import com.ruoyi.ms.domain.MsPackage;
import com.ruoyi.ms.service.IMsPackageService;
import com.ruoyi.common.core.text.Convert;

import javax.annotation.Resource;

/**
 * 妙手订单信息Service业务层处理
 * 
 * @author chdx
 * @date 2022-12-04
 */
@Service
public class MsPackageServiceImpl implements IMsPackageService
{

    private static final Logger log = LoggerFactory.getLogger(MsPackageServiceImpl.class);

    @Autowired
    private MsPackageMapper msPackageMapper;

    @Autowired
    private IMsOrderService orderService;

    @Autowired
    private IMsOrderIncomeService orderIncomeService;

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private ICommonService commonService;

    @Resource
    private MsPackageMap packageMap;


    /**
     * 查询妙手订单信息
     * 
     * @param msPackageId 妙手订单信息主键
     * @return 妙手订单信息
     */
    @Override
    public MsPackage selectMsPackageByMsPackageId(Long msPackageId)
    {
        return msPackageMapper.selectMsPackageByMsPackageId(msPackageId);
    }

    /**
     * 查询妙手订单信息列表
     * 
     * @param msPackage 妙手订单信息
     * @return 妙手订单信息
     */
    @Override
    public List<MsPackage> selectMsPackageList(MsPackage msPackage)
    {
        return msPackageMapper.selectMsPackageList(msPackage);
    }

    /**
     * 新增妙手订单信息
     * 
     * @param msPackage 妙手订单信息
     * @return 结果
     */
    @Override
    public int insertMsPackage(MsPackage msPackage)
    {
        return msPackageMapper.insertMsPackage(msPackage);
    }

    /**
     * 修改妙手订单信息
     * 
     * @param msPackage 妙手订单信息
     * @return 结果
     */
    @Override
    public int updateMsPackage(MsPackage msPackage)
    {
        return msPackageMapper.updateMsPackage(msPackage);
    }

    /**
     * 批量删除妙手订单信息
     * 
     * @param msPackageIds 需要删除的妙手订单信息主键
     * @return 结果
     */
    @Override
    public int deleteMsPackageByMsPackageIds(String msPackageIds)
    {
        return msPackageMapper.deleteMsPackageByMsPackageIds(Convert.toStrArray(msPackageIds));
    }

    /**
     * 删除妙手订单信息信息
     * 
     * @param msPackageId 妙手订单信息主键
     * @return 结果
     */
    @Override
    public int deleteMsPackageByMsPackageId(Long msPackageId)
    {
        return msPackageMapper.deleteMsPackageByMsPackageId(msPackageId);
    }

    @Override
    public void syncMsPackageInfo() throws IOException {

        log.info("开始同步妙手订单信息");

        String startTime = "2023-01-10+00:00:00";
        String endTime = "2023-01-23+00:00:00";
        //系统配置的起始时间
        //String startTime = commonService.selectConfigByKey(MsConstant.SYNC_MS_ORDER_START_TIME_CONFIG_KEY);
        Calendar now = Calendar.getInstance();
        int year = now.get(Calendar.YEAR);
        int month = now.get(Calendar.MONTH) + 1;
        int day = now.get(Calendar.DAY_OF_MONTH);
        int hours = now.get(Calendar.HOUR_OF_DAY);
        //同步结束小时为最近的一个小时59:59
        //String endTime = year + "-" + month + "-" + day + "+" + (hours - 1) + ":59:59";
        //下一次同步的时间点为当前小时的00:00
        String newStartTime = year + "-" + month + "-" + day + "+" + (hours) + ":00:00";

        int page = 1;
        int pageSize = 20;
        boolean isBreak = true;

        while (isBreak) {
            log.info("妙手订单同步开始时间:{}", startTime);
            log.info("妙手订单同步结束时间:{}", endTime);
            MsPackageResultResDto packageResultResDto = getMPackage(startTime, endTime, page, pageSize);
            if ("success".equals(packageResultResDto.getResult())) {
                for (MsPackageResDto packageResDto : packageResultResDto.getPackageResDtoList()) {
                    MsPackage msPackage = packageMap.mapPackageDtoToEntity(packageResDto);
                    msPackageMapper.insertMsPackage(msPackage);
                    MsOrderResDto msOrderResDto = packageResDto.getMsOrderResDto();
                    MsOrder msOrder = packageMap.mapOrderDtoToEntity(msOrderResDto);
                    orderService.insertMsOrder(msOrder);
                    MsOrderIncomeDetailResDto msOrderIncomeDetailResDto = msOrderResDto.getMsOrderIncomeDetailResDto();
                    MsOrderIncome msOrderIncome = packageMap.mapOrderIncomeDetailDtoToEntity(msOrderIncomeDetailResDto);
                    msOrderIncome.setOrderSn(msOrderResDto.getPlatformOrderSn());
                    orderIncomeService.insertMsOrderIncome(msOrderIncome);

                    OrderDto orderDto = new OrderDto();
                    orderDto.setOrderSn(msOrderResDto.getPlatformOrderSn());
                    orderDto.setShopId(GlobalConstant.COMMON_SHOP_ID);
                    orderDto.setRegion(msOrderResDto.getSite());
                    orderDto.setCurrency(msOrderResDto.getCurrency());
                    orderDto.setCod(String.valueOf(msOrderResDto.getIsCod()));
                    orderDto.setTotalAmount(msOrderResDto.getPayAmount());
                    orderDto.setOrderStatus(msOrderResDto.getPlatformOrderStatus());
                    orderDto.setShippingCarrier(msOrderResDto.getBuyerSelectLogistics());
                    orderDto.setPaymentMethod(msOrderResDto.getPaymentMethod());
                    orderDto.setEstimatedShippingFee(msOrderResDto.getEstimatedShippingFee());
                    orderDto.setMessageToSeller(msOrderResDto.getBuyerMessage());
                    orderDto.setDaysToShip(GlobalConstant.COMMON_DAY_TO_SHIP);
                    orderDto.setShipByDate(msOrderResDto.getGmtLastDelivery());
                    orderDto.setBuyerUserId(msOrderResDto.getBuyerId());
                    orderDto.setBuyerUsername(msOrderResDto.getBuyerUsername());
                    orderDto.setActualShippingFee(msOrderResDto.getActualShippingCost());
                    orderDto.setGoodsToDeclare(GlobalConstant.COMMON_GOODS_TO_DECLARE);
                    orderDto.setNote(msOrderResDto.getAppNote());
                    orderDto.setBuyerCancelReason(msOrderResDto.getCancelReason());
                    orderDto.setCancelBy(msOrderResDto.getCancelBy());
                    orderDto.setCheckoutShippingCarrier(msOrderResDto.getBuyerSelectLogistics());
                    orderDto.setSellerOrderStatus(msOrderResDto.getAppOrderStatus());
                    orderDto.setWarehouseOrderStatus(msOrderResDto.getAppOrderStatus());
                    orderDto.setWarehouseProcessStatus(GlobalConstant.WAREHOUSE_INIT_ORDER_STATUS);
                    orderDto.setTrackingNo(msOrderResDto.getTrackingNo());
                    orderDto.setOrderStartTime(msOrderResDto.getGmtOrderStart());
                    orderDto.setOrderModifiedTime(msOrderResDto.getGmtOrderModified());
                    orderDto.setPayTime(msOrderResDto.getGmtPay());
                    orderDto.setLastDeliveryTime(msOrderResDto.getGmtLastDelivery());
                    orderDto.setDeliveryTime(msOrderResDto.getGmtDelivery());
                    orderDto.setRefundTime(msOrderResDto.getGmtRefund());
                    orderDto.setFinishTime(msOrderResDto.getGmtFinish());

                    OrderIncomeDto orderIncomeDto = new OrderIncomeDto();
                    orderIncomeDto.setOrderSn(msOrderResDto.getPlatformOrderSn());
                    orderIncomeDto.setEscrowAmount(msOrderIncomeDetailResDto.getEscrowAmount());
                    orderIncomeDto.setBuyerTotalAmount(msOrderIncomeDetailResDto.getTotalAmount());
                    orderIncomeDto.setSellerDiscount(msOrderResDto.getDiscountAmount());
                    orderIncomeDto.setVoucherFromSeller(msOrderIncomeDetailResDto.getVoucherSeller());
                    orderIncomeDto.setVoucherFromShopee(msOrderIncomeDetailResDto.getVoucher());
                    orderIncomeDto.setCoins(msOrderIncomeDetailResDto.getCoin());
                    orderIncomeDto.setBuyerPaidShippingFee(msOrderIncomeDetailResDto.getBuyerPaidShippingFee());
                    orderIncomeDto.setCrossBorderTax(msOrderIncomeDetailResDto.getCrossBorderTax());
                    orderIncomeDto.setCommissionFee(msOrderIncomeDetailResDto.getCommissionFee());
                    orderIncomeDto.setServiceFee(msOrderIncomeDetailResDto.getServiceFee());
                    orderIncomeDto.setSellerTransactionFee(msOrderIncomeDetailResDto.getSellerTransactionFee());
                    orderIncomeDto.setSellerCoinCashBack(msOrderIncomeDetailResDto.getSellerCoinCashBack());
                    orderIncomeDto.setFinalShippingFee(msOrderIncomeDetailResDto.getFinalShippingFee());
                    orderIncomeDto.setActualShippingFee(msOrderIncomeDetailResDto.getActualShippingCost());
                    orderIncomeDto.setShopeeShippingRebate(msOrderIncomeDetailResDto.getShippingFeeRebate());
                    orderIncomeDto.setSellerVoucherCode(msOrderIncomeDetailResDto.getVoucherCode());
                    orderIncomeDto.setCreditCardPromotion(msOrderIncomeDetailResDto.getCreditCardPromotion());
                    orderIncomeDto.setCreditCardTransactionFee(msOrderIncomeDetailResDto.getCreditCardTransactionFee());

                    OrderInfoDto orderInfoDto = new OrderInfoDto();
                    orderInfoDto.setOrderDto(orderDto);
                    orderInfoDto.setOrderIncomeDto(orderIncomeDto);
                    orderInfoService.addOrderInfo(orderInfoDto);
                }
                int total = packageResultResDto.getTotal();
                if (total < (page - 1) * pageSize) {
                    isBreak = false;
                }
                page++;
            }else {
                isBreak = false;
                log.info("同步妙手订单失败");
            }
        }

        log.info("妙手订单下一次同步开始时间:{}", newStartTime);
        //commonService.updateConfigByKey(MsConstant.SYNC_MS_ORDER_START_TIME_CONFIG_KEY, newStartTime);
        log.info("结束同步妙手订单信息");

    }

    @Override
    public void syncMsPackageInfoByOrderSn(String platformOrderSn, String orderStatus) throws IOException {
        MsPackageResultResDto packageResultResDto = getMPackage(platformOrderSn);
        if ("success".equals(packageResultResDto.getResult())) {
            for (MsPackageResDto packageResDto : packageResultResDto.getPackageResDtoList()) {

                MsPackage msPackage = packageMap.mapPackageDtoToEntity(packageResDto);
                MsOrderResDto msOrderResDto = packageResDto.getMsOrderResDto();

                //判断平台的订单状态是否更新
                if (!msOrderResDto.getPlatformOrderStatus().equals(orderStatus)) {
                    //更新包裹信息
                    MsPackage msPackageQuery = new MsPackage();
                    msPackageQuery.setPlatformOrderSn(platformOrderSn);
                    List<MsPackage> msPackageList = msPackageMapper.selectMsPackageList(msPackageQuery);
                    if (CollectionUtil.isNotEmpty(msPackageList) && msPackageList.size() == 1) {
                        msPackage.setMsPackageId(msPackageList.get(0).getMsPackageId());
                        msPackageMapper.updateMsPackage(msPackage);
                    }else {
                        log.info("MsPackage表{}不存在或者有多条数据",platformOrderSn);
                    }

                    //刚更新订单信息
                    MsOrder msOrder = packageMap.mapOrderDtoToEntity(msOrderResDto);
                    MsOrder msOrderQuery = new MsOrder();
                    msOrderQuery.setPlatformOrderSn(platformOrderSn);
                    List<MsOrder> msOrderList = orderService.selectMsOrderList(msOrderQuery);
                    if (CollectionUtil.isNotEmpty(msOrderList) && msOrderList.size() == 1) {
                        msOrder.setOrderId(msOrderList.get(0).getOrderId());
                        orderService.updateMsOrder(msOrder);
                    }else {
                        log.info("MsOrder表{}不存在或者有多条数据",platformOrderSn);
                    }

                    //更新虾皮订单信息
                    OrderDto orderDto = new OrderDto();
                    orderDto.setOrderSn(platformOrderSn);
                    orderDto.setOrderStatus(msOrderResDto.getPlatformOrderStatus());
                    orderDto.setOrderModifiedTime(msOrderResDto.getGmtOrderModified());
                    orderDto.setPayTime(msOrderResDto.getGmtPay());
                    orderDto.setLastDeliveryTime(msOrderResDto.getGmtLastDelivery());
                    orderDto.setDeliveryTime(msOrderResDto.getGmtDelivery());
                    orderDto.setRefundTime(msOrderResDto.getGmtRefund());
                    orderDto.setFinishTime(msOrderResDto.getGmtFinish());
                    orderInfoService.updateOrderStatus(orderDto);
                }
            }
        }
    }

    /**
     * 更新订单收入
     *
     * @param platformOrderSn
     */
    @Override
    public void syncMSPackageIncome(String platformOrderSn) throws IOException {
        log.info("开始同步{}订单收入信息", platformOrderSn);
        MsPackageResultResDto packageResultResDto = getMPackage(platformOrderSn);
        if ("success".equals(packageResultResDto.getResult())) {
            for (MsPackageResDto packageResDto : packageResultResDto.getPackageResDtoList()) {
                MsPackage msPackage = packageMap.mapPackageDtoToEntity(packageResDto);
                MsOrderResDto msOrderResDto = packageResDto.getMsOrderResDto();
                MsOrderIncomeDetailResDto msOrderIncomeDetailResDto = msOrderResDto.getMsOrderIncomeDetailResDto();
                MsOrderIncome msOrderIncome = packageMap.mapOrderIncomeDetailDtoToEntity(msOrderIncomeDetailResDto);

                if (msOrderIncome.getFinalShippingFee().compareTo(new BigDecimal(0)) != 1) {
                    MsOrderIncome msOrderIncomeQuery = new MsOrderIncome();
                    msOrderIncomeQuery.setOrderSn(platformOrderSn);
                    List<MsOrderIncome> msOrderIncomeList = orderIncomeService.selectMsOrderIncomeList(msOrderIncomeQuery);
                    if (CollectionUtil.isNotEmpty(msOrderIncomeList) && msOrderIncomeList.size() == 1) {
                        msOrderIncome.setOrderIncomeId(msOrderIncomeList.get(0).getOrderIncomeId());
                        orderIncomeService.updateMsOrderIncome(msOrderIncome);
                    }else {
                        log.info("MsOrderIncome{}不存在或者有多条数据",platformOrderSn);
                    }

                    OrderIncomeDto orderIncomeDto = new OrderIncomeDto();
                    orderIncomeDto.setOrderSn(msOrderResDto.getPlatformOrderSn());
                    orderIncomeDto.setEscrowAmount(msOrderIncomeDetailResDto.getEscrowAmount());
                    orderIncomeDto.setBuyerTotalAmount(msOrderIncomeDetailResDto.getTotalAmount());
                    orderIncomeDto.setSellerDiscount(msOrderResDto.getDiscountAmount());
                    orderIncomeDto.setVoucherFromSeller(msOrderIncomeDetailResDto.getVoucherSeller());
                    orderIncomeDto.setVoucherFromShopee(msOrderIncomeDetailResDto.getVoucher());
                    orderIncomeDto.setCoins(msOrderIncomeDetailResDto.getCoin());
                    orderIncomeDto.setBuyerPaidShippingFee(msOrderIncomeDetailResDto.getBuyerPaidShippingFee());
                    orderIncomeDto.setCrossBorderTax(msOrderIncomeDetailResDto.getCrossBorderTax());
                    orderIncomeDto.setCommissionFee(msOrderIncomeDetailResDto.getCommissionFee());
                    orderIncomeDto.setServiceFee(msOrderIncomeDetailResDto.getServiceFee());
                    orderIncomeDto.setSellerTransactionFee(msOrderIncomeDetailResDto.getSellerTransactionFee());
                    orderIncomeDto.setSellerCoinCashBack(msOrderIncomeDetailResDto.getSellerCoinCashBack());
                    orderIncomeDto.setFinalShippingFee(msOrderIncomeDetailResDto.getFinalShippingFee());
                    orderIncomeDto.setActualShippingFee(msOrderIncomeDetailResDto.getActualShippingCost());
                    orderIncomeDto.setShopeeShippingRebate(msOrderIncomeDetailResDto.getShippingFeeRebate());
                    orderIncomeDto.setSellerVoucherCode(msOrderIncomeDetailResDto.getVoucherCode());
                    orderIncomeDto.setCreditCardPromotion(msOrderIncomeDetailResDto.getCreditCardPromotion());
                    orderIncomeDto.setCreditCardTransactionFee(msOrderIncomeDetailResDto.getCreditCardTransactionFee());
                    orderInfoService.updateOrderIncome(orderIncomeDto);

                    log.info("完成{}订单收入信息更新", platformOrderSn);
                }else {
                    log.info("{}订单收入信息未更新", platformOrderSn);
                }
            }
            orderInfoService.updatePurchasePrice(platformOrderSn);
        }
        log.info("结束同步{}订单收入信息", platformOrderSn);
    }

    private MsPackageResultResDto getMPackage(String startTime, String endTime, int page, int pageSzie) throws IOException {
        HttpClient httpClient = new DefaultHttpClient();
        String url = "https://erp.91miaoshou.com/api/order/package/searchOrderPackageList?pageSize="+ pageSzie +"&page=" + page + "&goodsSkuOuterIdRp=ss&platformOuterSkuIdRp=ss&gmtOrderStartFrom="+startTime + "&gmtOrderStartTo=" + endTime +"&platform=shopee&appPackageTab=all&sortField=gmtOrderStart&sortType=desc&waitProcessTab=all";
        HttpGet httpGet = new HttpGet(url);

        httpGet.addHeader("Cookie", "_ati=7193560746238; Hm_lvt_f8ed6fbfb0aeb9e90565d1fc07042047=1663485776; Hm_lvt_1db4313a9f5c46a5e1814ce0b93ecd08=1667405296,1669132341,1669420815; mserp=9rgh7p02a0ah2dea196jduilu3; __51cke__=; mserp_sst=9rgh7p02a0ah2dea196jduilu3; useOldOpVersion=0; __tins__20620655={\"sid\": 1669513111624, \"vd\": 1, \"expires\": 1669514911624}; __51laig__=4; accountId=1207036; Hm_lpvt_1db4313a9f5c46a5e1814ce0b93ecd08=1669518537");
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String responseStr = EntityUtils.toString(entity, "UTF-8");
        MsPackageResultResDto packageResultResDto = new Gson().fromJson(responseStr, MsPackageResultResDto.class);

        return packageResultResDto;
    }

    private MsPackageResultResDto getMPackage(String platfromOrderSn) throws IOException {
        HttpClient httpClient = new DefaultHttpClient();
        String url = "https://erp.91miaoshou.com/api/order/package/searchOrderPackageList?pageSize=10&page=1&goodsSkuOuterIdRp=ss&platformOuterSkuIdRp=ss&platformOrderSns=" + platfromOrderSn + "&appPackageTab=&sortField=gmtOrderStart&sortType=desc&waitProcessTab=all";
        HttpGet httpGet = new HttpGet(url);

        httpGet.addHeader("Cookie", "_ati=7193560746238; Hm_lvt_f8ed6fbfb0aeb9e90565d1fc07042047=1663485776; Hm_lvt_1db4313a9f5c46a5e1814ce0b93ecd08=1667405296,1669132341,1669420815; mserp=9rgh7p02a0ah2dea196jduilu3; __51cke__=; mserp_sst=9rgh7p02a0ah2dea196jduilu3; useOldOpVersion=0; __tins__20620655={\"sid\": 1669513111624, \"vd\": 1, \"expires\": 1669514911624}; __51laig__=4; accountId=1207036; Hm_lpvt_1db4313a9f5c46a5e1814ce0b93ecd08=1669518537");
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String responseStr = EntityUtils.toString(entity, "UTF-8");
        MsPackageResultResDto packageResultResDto = new Gson().fromJson(responseStr, MsPackageResultResDto.class);

        return packageResultResDto;
    }


    public static void main(String[] args) throws IOException, ParseException {
        MsPackageServiceImpl packageServiceImpl = new MsPackageServiceImpl();
        //packageServiceImpl.getMPackage("2022-11-01+00:00:00","2022-12-31+00:00:00",1,20);

        Calendar now = Calendar.getInstance();
        int year = now.get(Calendar.YEAR);
        int month = now.get(Calendar.MONTH) + 1;
        int day = now.get(Calendar.DAY_OF_MONTH);
        int hours = now.get(Calendar.HOUR_OF_DAY);
        //同步结束小时为最近的一个小时59:59
        String endTime = year + "-" + month + "-" + day + "+" + (hours - 1) + ":59:59";
        //下一次同步的时间点为当前小时的00:00
        String newStartTime = year + "-" + month + "-" + day + "+" + (hours) + ":00:00";
        System.out.println(endTime);
        System.out.println(newStartTime);
    }
}
